/*复用头部*/
define(["jquery","bootstrap"],function($){
	function Header(){
		this.load();
	}
	
	
	Header.prototype = {
		constructor:Header,
		load: function(){
			$.ajax("/html/include/header.html")
			 .done($.proxy(this.headerHandler,this));
		},
		//处理头部加载任务
		headerHandler: function(data){
			$("header").html(data);	
			//切换页面
			var url = location.href;	
			$(".manage li a").each(function(){
				if ((url + '/').indexOf($(this).attr('href')) > -1&&$(this).attr('href')!='') {
					$(this).parents("li").addClass('active');			
				} else {
					$(this).parents("li").removeClass('active');
				}
			});
			
			//注册监听事件
			this.addListener();
			//生成验证码
			this.genCode();
			//加载登录成功的用户信息
			this.loadUser();
		},
		//注册监听事件
		addListener:function(){	
			//注册
			$(".btn-register").on("click",this.registerHandler);
			//登录
			$(".btn-login").on("click",this.loginHander);
			//点击验证码刷新
			$(".code").click(this.genCode);
			//失去焦点验证验证码
			$(".input-code").on("blur",this.inputCodeHandler);
			//注销用户
			$(".login-out").on("click",this.loginOutHandler);
		},
		//注册模块
		registerHandler:function(){
			const data = $(".form-register").serialize();
			const url = "/api/users/register";
			$.post(url,data,(data)=>{
				console.log(data);
				if(data.res_body.status === 1){//注册成功
					sessionStorage.username = data.res_body.data.username;
					location.reload();
				}else{//注册失败
					$(".register-error").removeClass("hidden");
				}
			},"json");
		},
		//登录模块
		loginHander(){						
			const data = $(".form-login").serialize();
			const url = "/api/users/login";
			$.post(url,data,(data)=>{
				console.log(data);
				if(data.res_body.status === 1){//登录成功
					sessionStorage.username = data.res_body.data.username;									
					location.reload();
				}else{
					$(".login-error").removeClass("hidden");
				}
			},"json");
		},
		//生成验证码
		genCode(){
			$.getJSON("/api/captcha",(data)=>{
				$(".code").html(data.res_body.data);
			});
		},
		//校验验证码
		inputCodeHandler(event){
			const code = $(event.target).val();
			$.getJSON("/api/captcha/verify",{code},(data)=>{
				if(!data.res_body.valid){
					$(".code-error").removeClass("hidden");	
				}
			});
		},
		//加载登录成功的用户信息
		loadUser(){
			const user = sessionStorage.username;
			if(user){
				$(".login-success").removeClass("hidden").prev().addClass("hidden");
				$(".login-success li:first>a").html("欢迎您："+user);
			}		
		},
		//注销用户
		loginOutHandler(){
			sessionStorage.removeItem("username");
			$.getJSON("/api/users/logout",(data)=>{
				if(data.res_body.status === 1){
					location.reload();
				}
			});
		}
	}
	new Header();
});
